package com.reebake.ideal.permission.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.reebake.ideal.permission.constants.RoleStatus;
import com.reebake.ideal.permission.entity.Role;
import com.reebake.ideal.permission.entity.UserRole;
import com.reebake.ideal.permission.service.PermissionAuthService;
import com.reebake.ideal.permission.service.RoleService;
import com.reebake.ideal.permission.service.UserRoleService;
import com.reebake.ideal.permission.vo.RoleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/role")
@RequiredArgsConstructor
public class RolePlusController {
    private final UserRoleService userRoleService;
    private final PermissionAuthService permissionAuthService;
    private final RoleService roleService;

    @GetMapping("/user/{userId}")
    public List<String> queryByUserId(@PathVariable String userId){
        LambdaQueryWrapper<UserRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserRole::getUserId, userId);
        return userRoleService.list(queryWrapper).stream().map(UserRole::getRoleId).toList();
    }

    @PostMapping("user/{userId}")
    public void saveUserRoleByUser(@PathVariable String userId, @RequestBody List<String> roleIds){
        if(CollectionUtil.isEmpty(roleIds)){
            return;
        }
        permissionAuthService.saveUserRole(userId, roleIds);
    }

    @GetMapping("/list/enabled")
    public List<RoleVO> queryAllEnabled(){
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Role::getStatus, RoleStatus.ENABLED);
        return BeanUtil.copyToList(roleService.list(queryWrapper), RoleVO.class);
    }
}
